package com.ludomancy.gamelib;

import java.applet.Applet;
import java.applet.AudioClip;
import java.awt.EventQueue;
import java.awt.Image;
import java.awt.MediaTracker;
import java.net.URL;


public abstract class GameApplet extends Applet implements ResourceLoader, Runnable
{
	public GameCanvas gameCanvas = null;
    Thread thread;
    public static GameApplet gameAppletInstance;
    public static int fps;
    private Music lastPlaying;
    private boolean run = true;
    
    public GameApplet()
    {
    	gameAppletInstance = this;
    	fps = 28;
    }
    
	public void init()
	{
		ResourceManager.init(this, "/");
		gameCanvas = new GameCanvas();
		gameCanvas.setSize(getSize());
		add(gameCanvas);
		validate();
		setVisible(true);
		onInit();
    	thread = new Thread(this);
    	thread.start();
	}
	
	protected abstract void onInit();
	protected abstract void onDisplay(boolean active);
	protected abstract void onDestroy();
	public abstract Theme getDefaultTheme();
	
    public void start()
    {
    	onDisplay(true);
    	if(lastPlaying != null)
    	{
    		lastPlaying.play();
    		lastPlaying = null;
    	}
	}
    
    public void stop()
    {
    	onDisplay(false);
    }
    
    public void destroy()
    {
    	onDestroy();
    	// pause all running music
    	Sound.soundActivated = false;
    	lastPlaying = Music.releaseAll();
    	run = false;
    	remove(gameCanvas);
    	try
		{
			thread.join();
		} 
    	catch (InterruptedException e)
		{
		}
    	thread = null;
    }
    
    public static long getFrameTime()
    {
    	return 1000/fps;
    }

	public void run()
	{
		while (run)
		{
			// Display the next frame of animation.
			try
			{
				if(gameCanvas != null && gameCanvas.isValid())
				{
					EventQueue.invokeAndWait(gameCanvas);
				}
			} 
			catch (Exception e)
			{
				e.printStackTrace();
			}

			// Delay depending on how far we are behind.
			try
			{
				long delay = (fps > 0) ? (1000 / fps) : 100;
				Thread.sleep(delay);
			} 
			catch (InterruptedException e)
			{
				break;
			}
		}
	}

	public AudioClip loadClip(String url)
	{
    	Class c = getClass();
    	URL urlRes = c.getResource(url);
        return Applet.newAudioClip(urlRes);
	}

	public Image loadImage(String file)
    {
        Image img = getImage(getClass().getResource(file));
        MediaTracker m = new MediaTracker(this);
        m.addImage( img, 1 );
        try
        {
        	m.waitForAll();
        }
        catch( InterruptedException e )
        {
        }
        return img;
    }
}
